package com.brother.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.log4j.Logger;

public class CountryLocation {
private static Logger log = Logger.getLogger(CountryLocation.class);		
public static String getCountryByIP(String ip){
	// <tr><th>Country:</th><td>Nigeria   <img
	String country = "";
	try{
		String httpUrl = (new StringBuilder("http://www.whatismyipaddress.com/ip/")).append(ip).toString();
	    URL url = new URL(httpUrl);
	    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
	    conn.setRequestMethod("GET");
	    conn.setRequestProperty("User-Agent", "\tMozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 (.NET CLR 3.5.30729)");
	    conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
	    conn.setRequestProperty("Host", "whatismyipaddress.com");
	    conn.setConnectTimeout(15000);
	    conn.setReadTimeout(10000);
	    InputStream in = conn.getInputStream();
	    BufferedReader bf = new BufferedReader(new InputStreamReader(in));
	    String line = null;
	    while((line = bf.readLine()) != null){ 
	        if(line.indexOf("<tr><th>Country:</th><td>") > -1){
	        	int start = line.indexOf("<tr><th>Country:</th><td>") + "<tr><th>Country:</th><td>".length();
	        	country = line.substring(start, line.indexOf("<img",start));
	        	country = country.trim().toLowerCase();
	        }
	    }
	    in.close();
	}catch(Exception e){
		log.error("", e);
	}
	return country;
}


}
